package com.quickcode.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by 张波 on 2019/10/24.
 */
@Slf4j
public class CountDownLatchExample2 {

    public final static int threadCount = 20;
    /*创建一个CountDownLatch对象*/
    public static final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
    /*构建一个线程池对象，实际开发过程中请通过ThreadPoolExecutor对象构造*/
    public static final ExecutorService executorService = Executors.newCachedThreadPool();

    public static void main(String[] args) {
        for (int i = 0; i < threadCount; ++i) {
            executorService.execute(() -> {
                try {
                    /*输出线程id然后休眠1000毫秒*/
                    Thread.sleep(1000);
                    log.info("thread:{}", Thread.currentThread().getId());
                } catch (InterruptedException e) {
                    log.error("exception:{}", e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            /*休眠100毫秒*/
            boolean flag = countDownLatch.await(1500, TimeUnit.MILLISECONDS);
            log.info("flag:{}", flag);
        } catch (InterruptedException e) {
            log.error("exception:{}", e);
        }
        log.info("finished");
        executorService.shutdown();
    }
}
